<template>
  <view class="charging">
    <!-- #ifdef H5 -->
    <van-nav-bar @click-left="onClickLeft" left-arrow title="充电中"></van-nav-bar>
    <!-- #endif -->
    <scroll-view class="charging-scroll" scroll-y="true" :style="styleHeight">
      <!-- 广告 -->
      <swiper
        v-if="data.adList.length > 0"
        class="ad-wrap"
        circular
        :indicator-dots="true"
        :autoplay="true"
        :interval="3000"
        :duration="500">
        <swiper-item v-for="(item, index) in data.adList" :key="index">
          <image class="swiper-item" :src="item.advPicture" @tap="tapAdv(item)"></image>
        </swiper-item>
      </swiper>
      <!-- 文字广告 -->
      <view v-if="data.adText.advContent" class="ad-text-box">
        <AdText :item="data.adText"></AdText>
      </view>

      <!-- 充电信息 -->
      <view class="info-wrap">
        <view v-if="appType !== 'lznt'" class="title text-bold">
          终端编码：{{ data.items.connectorId }}
        </view>
        <view v-else class="title text-bold">快捷码：{{ data.items.shortcutCode }}</view>
        <view v-if="data.items.equipmentType === 1" class="time-wrap">
          <text class="text1">剩余充电时长：</text>
          <!-- <text class="text2">{{ data.items.date }}</text>
          <text class="text3">:</text> -->
          <text class="text2">{{ data.items.hour }}</text>
          <text class="text3">:</text>
          <text class="text2">{{ data.items.minute }}</text>
        </view>
        <view v-else class="time-wrap"></view>
        <!-- 车动画 -->
        <view v-if="appType === 'lznt'" class="car-wrap">
          <div class="ellipse">
            <div class="ellipse1"></div>
            <div class="ellipse2"></div>
          </div>
          <div class="ellipse3"></div>
          <view class="pile"></view>
          <view class="car car1"></view>
        </view>
        <view v-else class="car-wrap">
          <div class="ellipse">
            <div class="ellipse1"></div>
            <div class="ellipse2"></div>
          </div>
          <div class="ellipse3"></div>
          <view class="car"></view>
        </view>
        <!-- SOC -->
        <view v-if="data.items.equipmentType === 1" class="flex-column soc-wrap">
          <view class="textt">当前电量</view>
          <view class="textb text-bold">
            {{ getVal(data.items.soc, '%') }}
          </view>
        </view>
        <view v-else class="flex-column soc-wrap">
          <view class="textb1">充电中</view>
        </view>
        <!--实时信息-->
        <view class="real-time-wrap">
          <view class="flex-column real-time">
            <view class="textt">
              <text class="iconfont icon-subtract"></text>
              已充时长
            </view>
            <view class="textb">
              {{ getVal(data.items.chargedTime, '分钟') }}
            </view>
          </view>
          <view class="flex-column real-time">
            <view class="textt">
              <text class="iconfont icon-money"></text>
              预计费用
            </view>
            <view class="textb">
              {{ getVal2(data.items.totalMoney, '￥', 2) }}
            </view>
          </view>
          <view class="flex-column real-time">
            <view class="textt">
              <text class="iconfont icon-power"></text>
              已充度数
            </view>
            <view class="textb">
              {{ getVal2(data.items.totalPower, '度') }}
            </view>
          </view>
          <view v-if="appType !== 'pnd'" class="flex-column real-time">
            <view class="textt">
              <text class="iconfont icon-ampere"></text>
              当前电流
            </view>
            <view class="textb">
              {{ getVal(data.items.current, 'A') }}
            </view>
          </view>
          <view v-if="appType === 'pnd'" class="flex-column real-time">
            <view class="textt">
              <text class="iconfont icon-ampere"></text>
              {{ !getPND() ? '当前电流' : 'A相电流' }}
            </view>
            <view class="textb">
              {{ getVal(data.items.currentA, 'A') }}
            </view>
          </view>
          <view v-if="getPND()" class="flex-column real-time">
            <view class="textt">
              <text class="iconfont icon-ampere"></text>
              B相电流
            </view>
            <view class="textb">
              {{ getVal(data.items.currentB, 'A') }}
            </view>
          </view>
          <view v-if="getPND()" class="flex-column real-time">
            <view class="textt">
              <text class="iconfont icon-ampere"></text>
              C相电流
            </view>
            <view class="textb">
              {{ getVal(data.items.currentC, 'A') }}
            </view>
          </view>
          <view v-if="!getPND()" class="line-row"></view>
          <view v-if="!getPND()" class="line-column"></view>
          <view v-if="getPND()" class="line-row line-row1"></view>
          <view v-if="getPND()" class="line-row line-row2"></view>
          <view v-if="getPND()" class="line-column line-column1"></view>
        </view>
      </view>
    </scroll-view>
    <!-- 底部按钮 -->
    <view class="bottom-wrap" :style="styleBntH">
      <button class="bnt-wrap bnt" @tap="tabStop">停止充电</button>
    </view>
    <!-- 启动/停止loading  120s -->
    <view v-if="data.loadType > 0" class="load-wrap">
      <view class="load-box">
        <view class="round-wrap">
          <view class="round r1"></view>
          <view class="round r2"></view>
          <view class="round r3"></view>
        </view>
        <view class="text">
          正在{{ data.loadType === 1 ? '开启' : '停止' }}充电{{ data.timeNum }}s
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import AdText from '@/components/adText/adText.vue';
import { getSystemInfo, getUserId, setOrderObj, setToastInstance, systemInfo } from '@mixins/info';
import { getChargeRecordData, queryStopCharge, getOrderStatus } from '@/service/apis/charge';
import { getVal, getVal2, noMultipleClicks, handleAd } from '@/utils/util';
import { queryChargingAdvertise } from '@/service/apis/advert';
import { getLocationInfo } from '@/utils/location';
// #ifdef MP-WEIXIN
import { useToast } from '@/components/wxToast';
setToastInstance(useToast());
// #endif

// 分享
onShareAppMessage(() => {
  return {
    title: '',
    path: '/pages/stationMap/stationMap',
  };
});

const appType = import.meta.env.VITE_VUE_APP_TYPE;

const getPND = () => {
  // return Boolean(appType === 'pnd');
  return Boolean(appType === 'pnd' && (data.items.currentB !== 0 || data.items.currentC !== 0));
};

let styleHeight = ref(`height: calc(100vh - 124rpx - 48rpx - ${getSystemInfo().safeBottom}px)`);
const styleBntH = `height: calc(124rpx + ${getSystemInfo().safeBottom}px)`;
// #ifdef H5
styleHeight.value = `height: calc(100vh - 124rpx - 48rpx - ${getSystemInfo().safeBottom}px - ${
  getSystemInfo().navHeight
}px)`;
// #endif

const data = reactive({
  id: '',
  adText: {} as any,
  adList: [] as any, // 轮播广告列表
  items: {} as any, // 充电信息
  timer: null as any,
  timer1: null as any,
  timer2: null as any,
  timeNum: 120,
  loadType: 1, // 1启动  2停止  0不显示
  pageType: '', // 跳转订单页面传参
  pageId: '', // 跳转订单页面传参
});

onLoad((option: any) => {
  data.id = option.id;
  getChargeData(false);
  getAdver();
  data.timer = setInterval(() => {
    getChargeData(true);
  }, 15 * 1000);
  startLoading();

  tabStop = noMultipleClicks(tabStop);
});

// 获取广告
const getAdver = () => {
  const userId = getUserId();
  const info = getLocationInfo();
  const obj = {
    cityName: info.cityName,
    userId: userId,
  };
  queryChargingAdvertise(obj).then((res: any) => {
    if (res) {
      if (res[0]?.length > 0) {
        data.adList = res[0];
      }
      if (res[1]?.length > 0) {
        data.adText = res[1][0];
      }
    }
  });
};

const tapAdv = (row: any) => {
  handleAd(row);
};

// 启动倒计时
const startLoading = () => {
  data.loadType = 1;
  data.timer1 = setInterval(() => {
    data.timeNum--;
    if (data.timeNum === 0) {
      clearTime();
      uni.showModal({
        content: '设备无法通讯，有异常可联系客服处理',
        showCancel: false,
        success: () => {
          uni.switchTab({
            url: '/pages/stationMap/stationMap',
          });
        },
      });
    }
  }, 1000);
};
const stopLoading = () => {
  data.loadType = 2;
  data.timer1 = setInterval(() => {
    data.timeNum--;
    if (data.timeNum === 0) {
      clearTime();
      uni.showModal({
        content: '设备无法通讯，有异常可联系客服处理',
        showCancel: false,
        success: () => {
          uni.switchTab({
            url: '/pages/order/order',
          });
        },
      });
    }
  }, 1000);
};
// 停止倒计时线程
const clearStart = () => {
  data.loadType = 0;
  clearInterval(data.timer1);
  data.timer1 = null;
  data.timeNum = 120;
};
const clearStop = () => {
  data.loadType = 0;
  clearInterval(data.timer2);
  data.timer2 = null;
  data.timeNum = 120;
};

const padding2 = (num: any) => {
  if (String(num).length < 2) {
    return `0${num}`;
  }
  return String(num);
};

// 查询实时数据
const getChargeData = (flag: boolean) => {
  getChargeRecordData(data.id, flag).then((res: any) => {
    switch (res?.chargeRecordStatus) {
      case 1: // 启动中
        break;
      case 2: // 充电中
        data.items = res;
        // data.items.date = '00';
        if (!res.leftTime) {
          data.items.hour = '--';
          data.items.minute = '--';
        } else {
          data.items.hour = '00';
          data.items.minute = '00';
          if (res.leftTime < 60) {
            data.items.minute = padding2(res.leftTime);
          } else {
            data.items.hour = padding2(parseInt(String(res.leftTime / 60)));
            data.items.minute = padding2(res.leftTime % 60);
          }
          // else if (res.leftTime < 60 * 24) {
          //   data.items.hour = padding2(parseInt(String(res.leftTime / 60)));
          //   data.items.minute = padding2(res.leftTime % 60);
          // } else {
          //   const t1 = parseInt(String(res.leftTime / 60));
          //   data.items.date = padding2(parseInt(String(t1 / 24)));
          //   data.items.hour = padding2(t1 % 24);
          //   data.items.minute = padding2(res.leftTime % 60);
          // }
        }
        clearStart();
        break;
      case 3: // 停止中
        break;
      case 4: //已停止
        const msg =
          data.loadType === 2 ? '停止充电成功！' : res.stopMsg ? res.stopMsg : '订单已结束！';
        clearTime();
        clearStop();
        uni.showModal({
          content: msg,
          showCancel: false,
          success: (e: any) => {
            if (e.confirm) {
              getStatusOrder();
              // data.pageType = 'history';
              // uni.switchTab({
              //   url: '/pages/order/order',
              // });
            }
          },
        });
        break;
      case 5: // 未知
        break;
      case 6: // 异常
        clearTime();
        clearStop();
        uni.showModal({
          content: '订单异常，请联系客服处理！',
          showCancel: false,
          success: (e: any) => {
            if (e.confirm) {
              data.pageType = 'pending';
              uni.switchTab({
                url: '/pages/order/order',
              });
            }
          },
        });
        break;
    }
  });
};
// 清除实时数据线程
const clearTime = () => {
  clearInterval(data.timer);
  data.timer = null;
};

// 停止充电
let tabStop = () => {
  uni.showModal({
    content: '您确认要停止充电吗？',
    success: (e: any) => {
      if (e.confirm) {
        queryStopCharge({
          connectorId: data.items.connectorId,
          startChargeSeq: data.id,
          stopReason: '20301',
        }).then((res: any) => {
          stopLoading();
        });
      }
    },
  });
};

// 查看订单状态
const getStatusOrder = () => {
  uni.showLoading({
    title: '加载中',
  });
  const timer = setTimeout(() => {
    getOrderStatus(data.id).then((res: any) => {
      // CURRENT_ORDER 实时订单
      // ABNORMAL_ORDER 异常订单
      // HISTORY_ORDER 历史订单
      // PENDINGORDER 待处支付订单
      // if (appType === 'baseline' || appType === 'lznt') {
      data.pageType = 'history';
      if (res.orderState === 'ABNORMAL_ORDER') {
        data.pageType = 'pending';
      } else if (res.orderState === 'PENDINGORDER') {
        data.pageId = res.orderId;
        data.pageType = 'unpay';
      } else {
        data.pageId = res.orderId;
        data.pageType = 'history';
      }
      setOrderObj({ pageType: data.pageType, pageId: data.pageId });
      console.log('data.pageType====', data.pageType);

      if (data.pageType === 'unpay') {
        uni.redirectTo({
          url: `/pages/orderDetails/unpayDetails?id=${data.pageId}`,
        });
      } else if (data.pageType === 'history') {
        uni.redirectTo({
          url: `/pages/orderDetails/historyDetails?id=${data.pageId}`,
        });
      } else {
        uni.reLaunch({
          url: '/pages/order/order',
        });
      }
      // uni.reLaunch({
      //   url: `/pages/order/order`,
      // });

      // } else {
      //   data.pageType = 'history';
      //   if (res === 'ABNORMAL_ORDER') {
      //     data.pageType = 'pending';
      //   } else if (res === 'PENDINGORDER') {
      //     data.pageType = 'unpay';
      //   }
      //   uni.reLaunch({
      //     url: '/pages/order/order',
      //   });
      // }
    });
    clearTimeout(timer);
  }, 2000);
};

onBeforeUnmount(() => {
  clearTime();
  clearStart();
  clearStop();
});

// onUnload(() => {
//   if (data.pageType) {
//     const obj = {
//       pageType: data.pageType,
//       pageId: data.pageId,
//     };
//     console.log('ccc-----', obj);
//     uni.$emit('pageType', obj);
//   }
// });

// #ifdef H5
const onClickLeft = () => {
  uni.navigateBack();
};
setTimeout(() => {
  const navBarEle = document.querySelector('.van-nav-bar') as HTMLElement;
  navBarEle.style.paddingTop = `${systemInfo.statusBarHeight}px`;
});
// #endif
</script>

<style lang="scss" scoped>
.charging {
  position: relative;
  // height: calc(100vh - 12px);
  height: 100%;
  padding: 12px 0;
  background-color: #f6f8ff;
  margin-bottom: constant(safe-area-inset-bottom);
  margin-bottom: env(safe-area-inset-bottom);
  // #ifdef H5
  padding-top: 0;
  // #endif
  &-scroll {
    // #ifdef H5
    padding-top: 12px;
    // #endif
  }

  .ad-wrap {
    height: 120px;
    margin: 0 16px;

    .swiper-item {
      width: 100%;
      height: 100%;
      border-radius: 12px;
    }
  }

  .ad-text-box {
    width: 100vw;
    margin: 10px 0;
  }

  .info-wrap {
    margin: 12px 16px;
    background-color: #fff;
    border-radius: 12px;

    .title {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 42px;
      background-color: $uni-color-primary;
      border-top-right-radius: 12px;
      border-top-left-radius: 12px;
      font-size: 12px;
      color: #fff;
    }

    .time-wrap {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 20px;
      margin-bottom: 38px;

      .text1 {
        line-height: 30px;
        font-size: 14px;
        color: #545454;
      }

      .text2 {
        display: flex;
        justify-content: center;
        align-items: center;
        min-width: 24px;
        height: 30px;
        margin-left: 4px;
        padding: 0 3px;
        line-height: 30px;
        font-size: 16px;
        color: #242424;
        border-radius: 4px;
        background: #fff;
        box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.25);
      }

      .text3 {
        margin-left: 4px;
        line-height: 30px;
        font-size: 14px;
        color: #000;
      }
    }

    .car-wrap {
      position: relative;
      display: flex;
      justify-content: center;

      .ellipse {
        position: absolute;
        width: 431px;
        height: 134px;
        top: 56px;
        border-radius: 50%;
        background-color: rgba(80, 115, 247, 0.1);
        animation-name: example;
        animation-duration: 2s;
        animation-iteration-count: infinite;
      }

      @keyframes example {
        0% {
          width: 431px;
          height: 134px;
          top: 56px;
        }

        50% {
          width: 451px;
          height: 144px;
          top: 61px;
        }

        100% {
          width: 431px;
          height: 134px;
          top: 56px;
        }
      }

      .ellipse1 {
        position: absolute;
        width: 307px;
        height: 96px;
        top: 19px;
        left: 62px;
        border-radius: 50%;
        background-color: rgba(80, 115, 247, 0.2);
        animation-name: example1;
        animation-duration: 2s;
        animation-iteration-count: infinite;
      }

      @keyframes example1 {
        0% {
          width: 307px;
          height: 96px;
          top: 19px;
          left: 62px;
        }

        50% {
          width: 327px;
          height: 106px;
          top: 14px;
          left: 52px;
        }

        100% {
          width: 307px;
          height: 96px;
          top: 19px;
          left: 62px;
        }
      }

      .ellipse2 {
        position: absolute;
        width: 263px;
        height: 72px;
        top: 20px;
        left: 84px;
        border-radius: 50%;
        /* background-color: rgba(80,115,247,0.5); */
        background-color: rgba(46, 82, 219, 0.5);
        animation-name: example2;
        animation-duration: 2s;
        animation-iteration-count: infinite;
      }

      @keyframes example2 {
        0% {
          width: 263px;
          height: 72px;
          top: 20px;
          left: 84px;
        }

        50% {
          width: 283px;
          height: 82px;
          top: 15px;
          left: 74px;
        }

        100% {
          width: 263px;
          height: 72px;
          top: 20px;
          left: 84px;
        }
      }

      .ellipse3 {
        position: absolute;
        width: 236px;
        height: 46px;
        top: calc(50% + 25px);
        left: calc(50% - 118px);
        margin: 0 auto;
        border-radius: 50%;
        background-color: rgba(19, 30, 133, 0.5);
        /* background-color: rgba(46,82,219,0.5); */
      }

      .car {
        position: relative;
        width: 210px;
        height: 113px;
        top: 5px;
        left: 0px;
        background-image: url($url + 'charge/car.png');
        background-size: 100%;
        background-repeat: no-repeat;
      }

      .car1 {
        top: 10px;
        left: -20px;
      }

      .pile {
        position: absolute;
        width: 70px;
        height: 136px;
        left: 220px;
        top: -31px;
        background-image: url($url + 'charge/pile.png');
        background-size: 100%;
        background-repeat: no-repeat;
      }
    }

    .soc-wrap {
      justify-content: center;
      align-items: center;
      margin-top: 80px;

      .textt {
        line-height: 22px;
        font-size: 14px;
        color: #828282;
      }

      .textb {
        line-height: 64px;
        font-size: 40px;
        color: #333333;
      }

      .textb1 {
        line-height: 64px;
        font-size: 24px;
        color: #333333;
      }
    }

    .real-time-wrap {
      position: relative;
      display: flex;
      align-items: center;
      flex-wrap: wrap; // 多行显示
      align-content: center;
      padding: 16px 0;

      .real-time {
        width: 50%;
        align-items: center;
        justify-content: center;
        margin: 10px 0;

        .textt {
          line-height: 22px;
          font-size: 14px;
          color: #858585;

          .iconfont {
            margin-right: 16;
            font-size: 16;
            color: $uni-color-primary;
          }
        }

        .textb {
          margin-top: 4px;
          line-height: 24px;
          font-size: 16px;
          color: #242424;
        }
      }

      .line-row {
        display: flex;
        position: absolute;
        width: 279px;
        height: 1px;
        left: calc(50% - 139px);
        background-color: #d4dbf5;
      }

      .line-row1 {
        top: 35%;
      }

      .line-row2 {
        top: 64%;
      }

      .line-column {
        position: absolute;
        width: 1px;
        height: 127px;
        left: 50%;
        background-color: #d4dbf5;
      }

      .line-column1 {
        height: 190px;
      }
    }
  }

  .bottom-wrap {
    display: flex;
    position: fixed;
    width: 100%;
    bottom: 0;
    background: #fff;
    border-top: 1px solid #e6e6e6;
    box-sizing: border-box;

    .bnt {
      height: 44px;
      width: 343px;
      margin-top: 9px;
      border-radius: 50px;
    }
  }
}

.load-wrap {
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.4);
  overflow: hidden;
  // #ifdef H5
  position: fixed;
  z-index: 900;
  // #endif

  .load-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 240px;
    height: 168px;
    background-color: #fff;
    border-radius: 8px;

    .text {
      margin-top: 40px;
      font-size: 16px;
      color: $uni-color-primary;
    }

    .round-wrap {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 60px;

      .round {
        width: 17px;
        height: 17px;
        margin: 3px;
        border-radius: 50%;
        background-color: $uni-color-primary;
      }

      .r1 {
        animation: a1 1s infinite ease-in-out;
      }

      .r2 {
        animation: a1 1s infinite ease-in-out;
        animation-delay: 0.25s;
      }

      .r3 {
        animation: a1 1s infinite ease-in-out;
        animation-delay: 0.5s;
      }

      @keyframes a1 {
        0%,
        100% {
          transform: translateY(0px);
        }

        25% {
          transform: translateY(-5px);
        }

        75% {
          transform: translateY(5px);
        }
      }
    }
  }
}
</style>
